package com.cqjtu.email;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import Decoder.BASE64Encoder;

/**
 * Created by Administrator on 2016/11/12 0012.
 */
public class STMPMain {

    private  String sender;
    private  String receiver;
    private  String password;
    private String subject;
    private String mainText;
    public STMPMain(String sender, String receiver, String password, String subject, String mainText) {
        this.sender = sender;
        this.receiver = receiver;
        this.password = password;
        this.subject = subject;
        this.mainText = mainText;
    }


    public void sendMail() throws IOException {
        Socket socket = null;
        String user = new BASE64Encoder().encode(sender.substring(0, sender.indexOf("@")).getBytes());
        String pass = new BASE64Encoder().encode(password.getBytes());

            socket = new Socket("smtp.163.com", 25);

            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter writter = new PrintWriter(outputStream, true);
            String s=reader.readLine();
            //HELO
            writter.println("HELO huan");
            Log.i("sendMain", " "+reader.readLine());
            //AUTH LOGIN
            writter.println("auth login");
            Log.i("sendMain", " "+reader.readLine());
            writter.println(user);
            Log.i("sendMain", " "+reader.readLine());
            writter.println(pass);
            Log.i("sendMain", " "+reader.readLine());
            //Above   Authentication successful <pre name="code" class="java">

            //Set mail from   and   rcpt to
            writter.println("mail from:<" + sender + ">");
            Log.i("sendMain", " "+reader.readLine());
            writter.println("rcpt to:<" + receiver + ">");
            Log.i("sendMain", " "+reader.readLine());

            //Set data
            writter.println("data");
            Log.i("sendMain", " "+reader.readLine());
            writter.println("subject:"+subject);
            writter.println("from:" + sender);
            writter.println("to:" + receiver);
            //writter.println("Content-Type: text/plain;charset=\"gb2312\"");
            writter.println();
            writter.println(mainText);
            writter.println(".");
            writter.println("");
            Log.i("sendMain", " "+reader.readLine());

            //Say GoodBye
            writter.println("rset");
            Log.i("sendMain", " "+reader.readLine());
            writter.println("quit");
            System.out.println(reader.readLine());

    }

}
